import java.util.Random;

public class RandomRedEnvelope extends RedEnvelope {
    double minMoney;
    int integerRemainMoney;
    int randomMoney;
    Random random;

    RandomRedEnvelope(double remainMoney, int remainPople) {
        random = new Random();
        minMoney = 0.01;
        this.remainMoney = remainMoney;
        this.remainPeople = remainPeople;
        integerRemainMoney = (int) (remainMoney * 100);
        if (integerRemainMoney < remainPeople * (int) (minMoney * 100)) {
            integerRemainMoney = remainPeople * (int) (minMoney * 100);
            this.remainMoney = (double) integerRemainMoney;
        }
    }

    public double giveMoney() {
        if (remainPeople <= 0) {
            return 0;
        }
        if (remainPeople == 1) {
            money = remainMoney;
            remainPeople--;
            return money;
        }
        randomMoney = random.nextInt(integerRemainMoney);
        if (randomMoney < (int) (minMoney * 100)) {
            randomMoney = (int) (minMoney * 100);
        }
        int leftOtherPeopleMoney = integerRemainMoney - randomMoney;
        int otherPeopleNeedMoney = (remainPeople - 1) * (int) (minMoney * 100);
        if (leftOtherPeopleMoney < otherPeopleNeedMoney) {
            randomMoney -= (otherPeopleNeedMoney - leftOtherPeopleMoney);
        }
        integerRemainMoney = integerRemainMoney - randomMoney;
        remainMoney = (double) (integerRemainMoney / 100.0);
        remainPeople--;
        money = (double) (randomMoney / 100.0);
        return money;
    }
}